package com.zidongxiangxi.rabbit.producer.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * rabbit连接工厂bean的后置加工
 *
 * @author chenxudong
 * @date 2020/11/07
 */
public class RabbitConnectionFactoryBeanPostProcessor implements BeanPostProcessor, Ordered {
	private final Logger logger = LoggerFactory.getLogger(RabbitConnectionFactoryBeanPostProcessor.class);

	@Override
	public int getOrder() {
		return LOWEST_PRECEDENCE - 2;
	}

	@Override
	public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
		if (!(bean instanceof CachingConnectionFactory)) {
			return bean;
		}
		Field publisherConfirmsField = ReflectionUtils.findField(CachingConnectionFactory.class, "publisherConfirms");
		if (Objects.isNull(publisherConfirmsField)) {
			return bean;
		}
		publisherConfirmsField.setAccessible(true);
		ReflectionUtils.setField(publisherConfirmsField, bean, true);
		return bean;
	}
}
